package com.mjf.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.mjf.utils.MyKafkaUtil;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.text.SimpleDateFormat;

/**
 * 过滤出每天不同的访问者（为日活做准备）
 *   1.识别出该访客打开的第一个页面（last_page_id 为空），表示这个访客开始进入应用
 *   2.由于访客可以在一天中多次进入应用，所以我们要在一天的范围内进行去重
 *
 * 数据流向：web/app -> nginx -> springboot -> kafka(ods) -> flinkApp -> kafka(dwd) -> flinkApp -> kafka(dwm)
 * 程序：gmall2020-mock-log-2020-12-18.jar -> flink-logger.sh(包含 nginx/springboot/kafka(ods)) -> BaseLogApp(包含 flinkApp/kafka(dwd)) -> UniqueVisitApp(包含 flinkApp/kafka(dwm))
 */
public class UniqueVisitApp {
    public static void main(String[] args) throws Exception {

        // 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

/*
        // 测试时关闭
        // 设置状态后端
        env.setStateBackend(new FsStateBackend("hdfs://hadoop102:9000/gmall-flink/checkpoint"));
        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
        env.getCheckpointConfig().setCheckpointTimeout(10000L);
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);

        // 设置重启策略
        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 10));
*/

        // 2.读取 Kafka dwd_page_log 主题数据
        String groupId = "UniqueVisitApp";
        String sourceTopic = "dwd_page_log";
        String sinkTopic = "dwm_unique_visit";
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil.getKafkaConsumer(sourceTopic, groupId));

        // 3.将每行数据转换为 Json 对象
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.map(JSON::parseObject);

        // 4.过滤数据 状态编程 只保留每个 mid 每天第一次登录的数据
        KeyedStream<JSONObject, String> keyedStream = jsonObjDS.keyBy(jsonObj -> jsonObj.getJSONObject("common").getString("mid"));

        SingleOutputStreamOperator<JSONObject> uvDS = keyedStream.filter(new RichFilterFunction<JSONObject>() {

            private ValueState<String> dateState;
            private SimpleDateFormat sdf;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("date-state", String.class);
                // 设置状态的 TTL 及 TTL 的更新方式
                StateTtlConfig ttlConfig = StateTtlConfig
                                .newBuilder(Time.hours(24))
                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                                .build();
                valueStateDescriptor.enableTimeToLive(ttlConfig);
                dateState = getRuntimeContext().getState(valueStateDescriptor);
                sdf = new SimpleDateFormat("yyyy-MM-dd");
            }

            @Override
            public boolean filter(JSONObject value) throws Exception {
                // 取出上一条页面信息
                String lastPageId = value.getJSONObject("page").getString("last_page_id");

                // 判断上一条页面是否为 null
                if (lastPageId == null || lastPageId.length() <= 0) {
                    // 取出状态数据
                    String lastDate = dateState.value();
                    // 取出今天的日期
                    String curDate = sdf.format(value.getLong("ts"));

                    // 判断两个日期是否相等
                    if (!curDate.equals(lastDate)) {
                        dateState.update(curDate);
                        return true;
                    }
                }
                return false;
            }
        });

        // 5.将数据写入 Kafka
        uvDS.print();
        uvDS.map(JSONAware::toJSONString).addSink(MyKafkaUtil.getKafkaProducer(sinkTopic));

        // 6.启动任务
        env.execute(UniqueVisitApp.class.getName());

    }
}
